package com.tc.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * Created by frederic.tang on 2017/3/28.
 */
public class DataMask {

    private static String base64Key = "lIVmrAZP0CeiOikMS3PWa6h/3fGWgfl4";
    private static Base64.Encoder encoder = Base64.getEncoder();
    private static Base64.Decoder decoder = Base64.getDecoder();

    /**
     * 数据加密
     *
     * @param raw 明文数据
     * @return 密文数据    null加密失败
     */
    public static String encode(String raw) {
        try {
            if (raw==null) return raw;
            Cipher c1 = Cipher.getInstance("DESede/ECB/PKCS5Padding");
            c1.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(decoder.decode(base64Key), "DESede"));
            return encoder.encodeToString(c1.doFinal(raw.getBytes("utf-8")));
        } catch (java.security.NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        } catch (javax.crypto.NoSuchPaddingException e2) {
            e2.printStackTrace();
        } catch (Exception e3) {
            e3.printStackTrace();
        }
        return null;
    }

    /**
     * 数据解密
     *
     * @param crypt 密文
     * @return 明文   null解密失败
     */
    public static String decode(String crypt) {
        try {
            if (crypt==null) return crypt;
            Cipher c1 = Cipher.getInstance("DESede/ECB/PKCS5Padding");
            c1.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decoder.decode(base64Key), "DESede"));
            return new String(c1.doFinal(decoder.decode(crypt)), "utf-8");
        } catch (java.security.NoSuchAlgorithmException e1) {
            return crypt;
        } catch (javax.crypto.NoSuchPaddingException e2) {
            return crypt;
        } catch (Exception e3) {
            return crypt;
        }
    }

}
